﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DTO;

namespace DAO
{

	public class CategoryDAO:IData
 	{
		public CategoryDAO(String myconnecString) : base(myconnecString) { }

		public  int OnSubmit(Category item, int t) {
			 return connec.ExecuteNonQuery("sp_Category", CommandType.StoredProcedure,new SqlParameter("@flag", t),
				 new SqlParameter("@" + Category.c_id, item.id), new SqlParameter("@" + Category.c_name, item.name),
				 new SqlParameter("@" + Category.c_create_on, item.create_on), new SqlParameter("@" + Category.c_orderId, item.orderId)); 
		}

		public  Category GetItem(IDataReader dr)
		{
			Category obj = new Category();
			obj.id = Convert.ToInt64(dr[Category.c_id]);
			obj.name = Convert.ToString(dr[Category.c_name]);
			obj.create_on = Convert.ToDateTime(dr[Category.c_create_on]);
			obj.orderId = Convert.ToInt32(dr[Category.c_orderId]);
			return obj;
		}

		public  List<Category> GetAll()
		{
			return GetAll("select * from " + Category.b_Category, CommandType.Text);
		}

		public  Category GetItemById(object id)
		{
			 return this.GetAll().FirstOrDefault(x => x.id == (long)id);
		}

        private List<Category> GetAll(String strSQL, CommandType commandtype)
        {
            List<Category> list = new List<Category>();
            SqlConnection connection = connec.Connection;
            SqlCommand command = new SqlCommand();
            command.CommandType = commandtype;
            command.CommandText = strSQL;
            command.Connection = connection;
            connection.Open();
            SqlDataReader reader;
            using (reader = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    list.Insert(0, GetItem(reader));
                }
                reader.Close();
            }
            connection.Close();
            return list;
        }
	}

 }
